package com.example.mysqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mysqlite.activity.BaseActivity;
import com.example.mysqlite.dao.StudentDao;
import com.example.mysqlite.dto.Student;
import com.example.mysqlite.util.DBhelpUtil;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Context mContext;

    private EditText etName,etSex,etAge,etClass;
    private EditText etSelectID,etDeleteID;
    private Button btnSave,btnSelect,btnDelete,btnSaveBitmap,btnSelectBitmap,btnUpdate;
    private TextView textView;
    private ImageView imageView;

    private DBhelpUtil dBhelpUtil;
    private StudentDao studentDao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        etName = findViewById(R.id.et_name);
        etSex = findViewById(R.id.et_sex);
        etAge = findViewById(R.id.et_age);
        etClass = findViewById(R.id.et_class);

        etSelectID =findViewById(R.id.et_select_id);
        etDeleteID = findViewById(R.id.et_delete_id);

        textView =findViewById(R.id.tv_data);
        imageView = findViewById(R.id.iv_image);

        //按钮
        btnSave = findViewById(R.id.tbn_save);
        btnSelect = findViewById(R.id.tbn_select);
        btnDelete = findViewById(R.id.tbn_delete);
        btnSaveBitmap = findViewById(R.id.btn_save_bitmap);
        btnSelectBitmap = findViewById(R.id.tbn_select_bitmap);
        btnUpdate = findViewById(R.id.btn_update);



        /**
         *
         * @param context   上下文
         * @param name      数据库名字
         * @param factory   游标工厂 null
         * @param version   自定义的数据库版本
         */
        dBhelpUtil = new DBhelpUtil(mContext,DBhelpUtil.DB_NAME,null,DBhelpUtil.DB_VERSION);
        studentDao = new StudentDao(MainActivity.this,dBhelpUtil);
        //保存数据事件
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存数据方法
                setDataSave();
            }
        });


        // 查询事件
        btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //查询数据
                selectDataByID();
            }
        });

        //修改事件
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateData();
            }
        });

        //删除事件
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteDataById();
            }
        });

        //跟新数据库版本后 增加了字段插入图片
        btnSaveBitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 获取文本信息
                    Student student = new Student();
                    student.name = etName.getText().toString();
                    student.sex = etSex.getText().toString();
                    student.age = Integer.valueOf(etAge.getText().toString());
                    student.clazz = etClass.getText().toString();

                    //图片
                    // 获取图片位图
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
                    //字节数组输出流
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    /** 把位图 转换 成字节数组输出流
                     *CompressFormat format,  格式
                     * int quality, 质量 0 - 100
                     * OutputStream stream 输出流
                     */
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);

                    student.logoHead = out.toByteArray();

                    studentDao.saveBitmap(student);
                    showToast("保存数据成功!");
                }catch (Exception e){
                    showToast("保存数据失败"+e.getMessage());
                }

            }
        });

        //查询展示图片
        btnSelectBitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectBitmapMethod();
            }
        });

    }




    /**保存数据*/
    public void setDataSave(){
        try {

            Student student = new Student();
            student.name = etName.getText().toString();
            student.sex = etSex.getText().toString();
            student.age = Integer.valueOf(etAge.getText().toString());
            student.clazz = etClass.getText().toString();

            Long result = studentDao.save(student);

            if(result != -1){
//                       Toast.makeText(getApplication(),"保存数据成功!返回插入行号是["+result+"]",Toast.LENGTH_SHORT).show();
                showToast("保存数据成功!返回插入行号是["+result+"]");
            }else{
                showToast("保存数据失败result["+result+"]");
            }

        }catch ( Exception e){
            e.printStackTrace();
        }
    }

    /**查询数据*/
    public void selectDataByID(){
        Long id = etSelectID.getText().toString().equals("") || etSelectID.getText().toString().equals(null) ? null:Long.valueOf(etSelectID.getText().toString());
        List<Student> data = studentDao.select(id);

        if(data.equals(null) || data.size() == 0){
            textView.setText("没有查到数据！");
        }else {
            textView.setText(data.toString());
        }

    }

    /**删除数据*/
    public  void deleteDataById(){
        Long id = etDeleteID.getText().toString().equals("") || etDeleteID.getText().toString().equals(null) ? null : Long.valueOf(etDeleteID.getText().toString());
        int result = studentDao.delete(id);
        if(result != 0){
            showToast("删除数据成功!删除了["+result+"]条记录！");
        }else{
            showToast("删除数据失败result["+result+"]");
        }


    }

    /**查询展示图片*/
    public void selectBitmapMethod(){
        try {
            Long id = etSelectID.getText().toString().equals("") || etSelectID.getText().toString().equals(null) ? 1:Long.valueOf(etSelectID.getText().toString());
            Student data = studentDao.selectBitmapById(id);
            if(data != null){
                // 把数据显示到页面
                etName.setText(data.name);
                etSex.setText(data.sex);
                etAge.setText(data.age+"");
                etClass.setText(data.clazz);
                //有数据再转
                if(data.logoHead != null){
                    textView.setText(" ");
                    // 把字节数组 转成位图
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data.logoHead,0,data.logoHead.length);
                    imageView.setImageBitmap(bitmap);
                }else{
                    textView.setText("没有图片数据！");
                }

            }else{
                textView.setText("没有查到数据！");
            }



        }catch (Exception e){
            e.printStackTrace();
            showToast("查询失败"+e.getMessage());
        }

    }

    /**更新**/
    public void updateData(){
        Long id = etDeleteID.getText().toString().equals("") || etDeleteID.getText().toString().equals(null) ? 1 : Long.valueOf(etDeleteID.getText().toString());

        Student student = new Student();
        student.name = etName.getText().toString();
        student.sex = etSex.getText().toString();
        student.age = Integer.valueOf(etAge.getText().toString());
        student.clazz = etClass.getText().toString();

        int result = studentDao.updateById(student,id);
        if(result != 0){
            showToast("修改数据成功!修改了["+result+"]条记录！");
        }else{
            textView.setText("没有【"+ id +"】这条记录！");
            showToast("修改数据失败result["+result+"]");
        }

    }

    public void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    //异步弹框
    public void showToastSync(String msg) {
        Looper.prepare();
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }
}